define("p_home", ["m_basepage",'text!T_UIHomeView',"m_tpl","m_swipe","m_zepto"], function(Basepage,T_UIHomeView) {
  var h = Basepage.extend({
              initialize: function() {
                  this.page.viewId = '#p-view-home',this.page.name = "p_view_home", this.page.html = '';
                  if(localStorage.getItem('homeIndex')&&localStorage.getItem('homeAd')&&localStorage.getItem('pointList')){
                    this.page.model = JSON.parse(localStorage.getItem('homeIndex'));
                    this.page.ad =   JSON.parse(localStorage.getItem('homeAd'));
                   this.page.pointList =   JSON.parse(localStorage.getItem('pointList'));
                      var superxjb = JSON.parse(localStorage.getItem('homeSuperXjb'));
                      if(!superxjb){
                         superxjb = {
                              spmhfincome:"--",
                              spmhfincomerate:"--"
                          }; 
                      }
                    this.page.html = (_.template(T_UIHomeView))({pointList:this.page.pointList,list:this.page.model,pageKey:'homeIndex',pageName:this.page.name,ad:this.page.ad,superxjb:superxjb});
                    this.pageAdd();
                  }
                  if(!sessionStorage.getItem('historyBack')||!this.page.ad||!this.page.model){
                      this._renderHTML();
                  }else{
                      sessionStorage.removeItem('historyBack');
                      this._initSwipe(this.page.ad);
                      this.init();
                  }
                  getCouponData();
              },
              enter: function() {
              },back: function() {
              },leave: function() {
              },_renderHTML: function() {
                  
                 if(islogin() &&　getLocVal('investorType') == '1'  ){
                    
                }
                  
                    var self = this;
                    var param =paramInterface.home;
                    param = $.extend(param,{
                         "noticeid":getLocVal("noticeid"),
                        'msglDate':getLocVal('msglDate'),
                        'newslDate':getLocVal('newslDate'),
                        "fundapiflag" : "0",
                        "interfaceversion": "2"
                    });
                    if(islogin()){
                        param = $.extend(param,{
                        "eqcustno" : localStorage.getItem("eqcustno"),
                        "datasource" : "DC"
                      });
                    }
                  toast();
                    nfApp._ajax(param,function(json){
                        closeToast();
                        if(json.code == SUCCESS_FLAG){
                          setLocVal("zeroflag",json.zeroflag);  
                          self.page.model = json.returnlist;
                          localStorage.setItem('homeIndex',JSON.stringify(self.page.model));
                          localStorage.setItem('homeAd',JSON.stringify(json.ad));
                          var superxjb = {
                              spmhfincome:json.spmhfincome,
                              spmhfincomerate:json.spmhfincomerate,
                              spmdate:json.spmdate.substr(5)
                          };
                          localStorage.setItem('homeSuperXjb',JSON.stringify(superxjb));
                           self.page.pointList = json.pointList;
                           localStorage.setItem('pointList',JSON.stringify(self.page.pointList));
                          self.page.html = (_.template(T_UIHomeView))({pointList:self.page.pointList,list:self.page.model,pageKey:'homeIndex',pageName:self.page.name,ad:json.ad,superxjb:superxjb});
                          self.pageAdd();
                          self._initSwipe(json.ad);
                          self.init();
                          if(json.noticeid&&json.noticecontent){
                            setLocVal("noticeid",json.noticeid);
                            dialog({
                              type:'alert',
                               content:json.noticecontent,
                            })
                          }

                        }else{
                            $toast(json.message);
                        }

                    })
              },_initSwipe: function(ad) {
                    var swiperHeight = window.innerWidth / 2.5 + 'px';
                    document.getElementById("home-ad-swiper").style.height = swiperHeight;
                    var e = this;
                    var str ='<div id="" class="swiper-container" style="width:100%;height: 100%">'
                      +'<div class="swiper-wrapper" >';
                    for (var i = 0; i < ad.length; i++) {
                    str+='<div class="swiper-slide"><img src="' + adPicUrl + ad[i].pic + '" style="width:100%;display:block;" /></div>'
                    }
                    str+='</div><div class="ad-pagination ub ub-ac ub-pc"></div></div>';
                    $('#home-ad-swiper').append(str);
                    e.mySwipe = new Swiper('.swiper-container', {
                        pagination: '.ad-pagination',
                        paginationClickable: '.ad-pagination',
                        effect: 'fade',
                        centeredSlides: true,
                        autoplay: 5000,
                        touchMoveStopPropagation:true,
                        preventClicksPropagation:true,
                        autoplayDisableOnInteraction: false,
                        onTap : function(swiper){
                            if(ad[swiper.activeIndex].url){
                                window.location.href = ad[swiper.activeIndex].url;
                            }                          
                        }
                    });
                    getMarketInfo(0)
              },bindMethod: function() {
                    var self = this, a = this.jdom;
                    a.delegate(".fundsItem", "click", function(e) {//查看基金详情
                      if($(e.target).hasClass('btn-buy'))return;//修复点击购买导致冒泡bug
                        var $this = $(this);
                        var _param = ($this.data('param')).split(',');
                        var returlist = self.page.model;
                        var fundDetail = returlist[parseInt(_param[0])];
                        setLocVal('fundDetail',JSON.stringify(fundDetail));
                        var param ={
                          fundcode:fundDetail.fundcode,
                          fundname:fundDetail.fundname,
                          fundtype:fundDetail.fundtype,
                          fundstate:fundDetail.fundstate,
                          fixFundFlag:fundDetail.fixFundFlag
                        }
                        piwikTrackEvent(Piwik_Event_Quota.index.category,Piwik_Event_Quota.index.recommend_fund.action,fundDetail.fundcode);    
                        location.href="fundDetail.html?v=20180614&"+paramSerialize(param)
                    }),a.delegate(".btn-buy", "click", function() {//现金宝列表
                            var $parent = $(this).parents('.fundsItem');
                            var _param = ($parent.data('param')).split(',');
                            var returlist = self.page.model;
                            var fundDetail = returlist[parseInt(_param[0])];
                            var fundtype = fundDetail.fundtype;
                            if (localStorage.getItem('originalString') == 'DCVALID' || localStorage.getItem('custType') == 'W') {
                                dialogConfirm('您尚未实名认证，不能进行此操作，是否立即实名认证？','实名认证','authenImme.html');
                                return;
                            }
                            // if (!judgeRisk()) {
                                // return;
                            // }
                             if (getLocVal("canBuy") == 'false') {
                                showRiskMessage();
                                return;
                            }
                            if( getLocVal('infoflag')  != 1 ){//信息不完整，购买任何基金前都要先补充完整
                                window.location.href  = "account/fillMes.html";
                                 return;
                            }
                            var param = {fundname:fundDetail.fundname,fundcode:fundDetail.fundcode,
                              fundstate:fundDetail.fundstate,fundtype:fundDetail.fundtype,
                            }
                            if(iswechat()&&!checkLock('4','')) {//微信登录增加手势密码验证
                                  return;
                            }
                            piwikTrackEvent(Piwik_Event_Quota.index.category,Piwik_Event_Quota.index.buy.action,fundDetail.fundcode);                                  
                            if(!islogin()){
                                 judgeJumpReloginUrl("login.html?autoHref=subscribe.html&"+paramSerialize(param));
                            }else{
                              if (localStorage.getItem('originalString') == 'DCVALID' || localStorage.getItem('custType') == 'W') {
                                  dialogConfirm('您尚未实名认证，不能进行此操作，是否立即实名认证？','实名认证','authenImme.html');
                              } else {
                                  window.location.href="subscribe.html?"+paramSerialize(param);
                              }
                            }
                    }),a.delegate(".superXjb-operation","click", function() {//  现金宝存入/取现//delegate无法阻止冒泡事件
                      var type = $(this).data('type');
                      if(iswechat()&&!checkLock('5','')) {//微信登录增加手势密码验证
                          return;
                      }
                      if(islogin()){
                          if (localStorage.getItem('originalString') == 'DCVALID' || localStorage.getItem('custType') == 'W') {
                              dialogConfirm('您尚未实名认证，不能进行此操作，是否立即实名认证？','实名认证','authenImme.html');
                              return;
                          }
                           if (getLocVal('moneyRiskLimit')==1&&getLocVal("canBuy") == 'false') {
                                showRiskMessage();
                                return;
                            }
                           if( getLocVal('infoflag')  != 1 ){
                                window.location.href  = "account/fillMes.html";
                                 return;
                            }
                          if(type=='storage'){
                              piwikTrackEvent(Piwik_Event_Quota.index.category,Piwik_Event_Quota.index.supermoney_charge.action,"");    
                              location.href ='storage.html';
                          }else{
                              piwikTrackEvent(Piwik_Event_Quota.index.category,Piwik_Event_Quota.index.balance_fixinvest.action,"");    
                              var j={
                                "function":"I005",
                                "sessionkey":getLocVal('sessionkey'),
                                'scope':'1',
                                'fundcode':superXjbCode,
                                'ywdm':'090'
                            }
                            toast();
                            nfApp._ajax(j,function(data){
                                closeToast();
                                if(data.code== SUCCESS_FLAG ){//定投列表
                                    if(data.returnlist&&data.returnlist.length>0){
                                        setLocVal('fixed_list', json2str(data.returnlist));
                                        location.href ='fixedStorageList.html';
                                    }else{
                                        location.href ='fixedStorage.html';
                                    }
                                }else if (data.code == Time_OUT) {
                                    judgeJumpReloginUrl('login.html');
                                }
                            });
                              //location.href ='fixedStorage.html';
                          }
                      }else {
                          judgeJumpReloginUrl('login.html');
                      }
                    }),a.delegate("#xjbDetail", "click", function(e) {//现金宝列表
                      if($(e.target).hasClass('superXjb-operation'))return;//修复点击购买导致冒泡bug
                      if(iswechat()&&!checkLock('6','')) {//微信登录增加手势密码验证
                          return;
                      }
                        var fundDetail = {
                            fundcode:superXjbCode,
                            fundname:'超级现金宝',
                        }
                        setLocVal('fundDetail', json2str(fundDetail));
                        piwikTrackEvent(Piwik_Event_Quota.index.category,Piwik_Event_Quota.index.supermoney.action,"");    
                      location.href ='xjbDetail.html';
                    });a.delegate("#index-rate-content", "click", function() {//现金宝列表
                        getMarketInfo(1);
                    });
                    $('.js-more').on('click',function(){
                        pageInit('p_view_funds');
                    });
                      $('.js-moreZX').on('click',function(){
                          location.href='zixun.html';
                      });
                       $('.js-zxItem').on('click',function(){
                            var index = $(this).data('index');
                            if(self.page.pointList[index].purl){
                                window.location.href = self.page.pointList[index].purl;
                            }else{
                                setLocVal('title',self.page.pointList[index].title);
                                setLocVal('medianame',self.page.pointList[index].medianame);
                                setLocVal('publishtime',self.page.pointList[index].publishtime);
                                setLocVal('id',self.page.pointList[index].id);
                                window.location.href = 'zxDetail.html';
                            }
                           
                            // $.extend(zxData[index],{type:1});//设置资讯详情类型
                            // setLocVal('zxDetail',JSON.stringify(zxData[index]));
                          // location.href='zixun.html';
                      });
                    $('.js-nav').delegate('li','click',function(){
                        var  self = this;
                        var index = $(this).data('index');
                        switch(index){
                            case 1:
                          //  $(self).find('.msg-count').remove();
                            piwikTrackEvent(Piwik_Event_Quota.index.category,Piwik_Event_Quota.index.view_info.action,"");    
                           // location.href='zixun.html';
                           location.href='wealth/themChooseFund.html';
                            break;
                            case 2:
                            //$(self).find('.msg-count').remove();location.href='publishMsgCenter.html';break;
                            if (!islogin()) {
                                  location.href='login.html';
                                  return;
                            } 
                            if (localStorage.getItem('originalString') == 'DCVALID' || localStorage.getItem('custType') == 'W') {
                                dialogConfirm('您尚未实名认证，不能进行此操作，是否立即实名认证？','实名认证','authenImme.html');
                                return;
                            }
                          // if (!judgeRisk()) {
                              // return;
                          // }
                          // if (getLocVal("canBuy") == 'false') {
                                // showRiskMessage();
                                // return;
                            // }
                            // if( getLocVal('infoflag')  != 1 ){//信息不完整，购买任何基金前都要先补充完整
                                // window.location.href  = "account/fillMes.html";
                                 // return;
                            // }
                            piwikTrackEvent(Piwik_Event_Quota.index.category,Piwik_Event_Quota.index.invest_area.action,"");
                            location.href='cleverInvest/investArea.html';break;
                            case 3:
                               piwikTrackEvent(Piwik_Event_Quota.index.category,Piwik_Event_Quota.index.fund_rank.action,"");    
                               location.href='fundRank.html?rankFlag=rxRank';
                               break;
                             // if (!islogin()) {
                                          // judgeJumpReloginUrl('login.html?autoHref=cleverInvest/eFixed_investment.html');
                                          // return;
                                    // } 
                                    // if(getLocVal('originalString') == 'DCVALID'||getLocVal('custType') == 'W') {//弱认证用户/代销客户
                                          // dialogConfirm('您尚未实名认证，不能进行此操作，是否立即实名认证？','实名认证','authenImme.html');
                                          // return;
                                    // }else {
                                        // location.href='cleverInvest/eFixed_investment.html';
                                    // }
                                    // break;
                            case 4:
                            piwikTrackEvent(Piwik_Event_Quota.index.category,Piwik_Event_Quota.index.new_financing.action,"");
                           if (!islogin()) {
                                  location.href='special/specialIndex.html';
                                  return;
                            } 
                            if(getLocVal('originalString') == 'DCVALID'||getLocVal('custType') == 'W') {//弱认证用户/代销客户
                                  dialogConfirm('您尚未实名认证，不能进行此操作，是否立即实名认证？','实名认证','authenImme.html');
                                  return;
                            }else {
                                toast();
                                 var j = {
                                         "function":"NF139",
                                        "sessionkey":getLocVal('sessionkey'),
                                        "type" : "1"
                                }
                                 toast();
                                 nfApp._ajax(j,function(data){
                                     console.log('是否是合格投资者返回：');
                                     console.log(json2str(data));
                                    closeToast();   
                                    if(data.code == SUCCESS_FLAG) {
                                        if(data.flag == 1){
                                            location.href='special/specialIndex.html';
                                        }else{
                                            location.href='special/sConfirm.html';
                                        }
                                    }
                                }); 
                            
                            }
                            
                            break;
                        }
                    });
                    
                     $('.js-checkComb').on("click",function(){
                         if (event != undefined) {
                            event.stopPropagation();
                        }
                         location.href='combinvest/combIntroduce.html';
                     });
                     $('.js-designComb').on("click",function(){
                         if (event != undefined) {
                            event.stopPropagation();
                        }
                        piwikTrackEvent(Piwik_Event_Quota.index.category,Piwik_Event_Quota.index.comb_invest_custom.action,"");                     
                         ///location.href='combinvest/combRisk.html';
                         location.href='combinvest/superFixed.html';
                     });
                    
                    
                    
                    
                    
                    
                    
              }});
             new h;
});

//判断是否显示头部
isHideTitle(browser.versions.mobile);
  //对头部进行变化
 // $('.virtualTitle').css({display:'none !important'});
 // $('.virtualTitle[page="p_view_home"]').css({display:''});
       

function getMarketInfo(clickFlag){
    var j = {
        "function" : "NF056",
    };
    nfApp._ajax(j, function(data) {
        if(data.code == SUCCESS_FLAG){
            $.each($('.index-name'),function(i,dom){
                 if(data.market.length>i){
                   // $(dom).text(data.market[i].name);
                     $(dom).text(data.market[i].shortname);
                }
            });
            $.each($('.index-price'),function(i,dom){
                 if(data.market.length>i){
                    var cssClass = ((data.market[i].rate+'').indexOf("-")>-1)?'tc-green':'tc-ff0';
                    $(dom).removeClass('c_green tc-ff0');
                    $(dom).addClass(cssClass).text(data.market[i].price);
                }
            });
            $.each($('.index-rate'),function(j,dom){
                 if(data.market.length>j){
                    var cssClass = ((data.market[j].rate+'').indexOf("-")>-1)?'tc-green':'tc-ff0';
                    $(dom).removeClass('c_green tc-ff0');
                    $(dom).addClass(cssClass).text(data.market[j].rate);
                }
            });
            if(!clickFlag&&$("#index-rate-content").hasClass('uhide')){
                $("#index-rate-content").removeClass("uhide");
                 var  times   = data.market.length/3;
                if( times > parseInt(times)  ){
                    var indexLoop = new IndexLoop(  Math.ceil(times) );
                }else{
                    var indexLoop = new IndexLoop( parseInt(times) );
                }
                // var indexLoop = new IndexLoop();
                indexLoop.loop();
            }
        }
    });
}




function IndexLoop(yTimes){
     this.oprateFlag  = 0;//0表示向上滚动，y为负数,增加操作
    this.currTimes  = 0;
    this.yTimes  = yTimes;
    this.DisY = window.getComputedStyle($('#zh-index')[0],null).height;
    this.view = 0;
    this.autoplayTimeoutId = null;
    this.loop = function(){
        var self = this;
        return setTimeout(function(){
            self.view = !self.view;
            var h = self.view?('-'+self.DisY):'0px';

            var h = '-'+(parseInt(self.DisY)*parseInt(self.currTimes))+'px';
            if(self.oprateFlag){
                self.currTimes--;
            }else{
               self.currTimes++; 
            }
            if(self.currTimes === (self.yTimes-1) ||  self.currTimes === 0){
                self.oprateFlag = !self.oprateFlag;
            }
            
            $('#index-view').css("-webkit-transform", "translateY(" +h+ ")");
            self.autoplayTimeoutId = self.loop();
        },5000);
    }
}





 function pageInit(nextPage){
        //对头部进行变化
        if(nextPage==''){
             $('.virtualTitle').css({display:'none !important'});
            $('.virtualTitle[page="p_view_home"]').css({display:''});
        }else{
            $('.virtualTitle').css({display:'none !important'});
            $('.virtualTitle[page="'+nextPage+'"]').css({display:''});
        }
        sessionStorage.setItem("indexHash","p_view_funds"); 
        //修改底部按钮激活
        $('.tab-actived').removeClass('tab-actived');
      $('[data-view="1"]').addClass('tab-actived');
      
      if( $('.virtualPage[page="p_view_funds"]').length <1 ){//表示还未加载，要进行加载
          var p_funds = require(['p_funds']);
      }
       var e = document.getElementsByTagName("header")[0].getElementsByTagName("style")[0];
        e.innerHTML = 'header{display: -webkit-box !important;display: box !important;}#wrapper{padding-top:2.5em;}#content{padding-top:2.5em;}';
         $('.virtualPage').css({display:'none !important'});
            $('.virtualPage[page="p_view_funds"]').css({display:'block !important'}); 
        
    }
